package com.leyou.order.web;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.order.client.AddressClient;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.fifter.LoginInterceptor;
import com.leyou.order.pojo.Order;
import com.leyou.order.service.OrderService;
import com.leyou.user.pojo.AddressDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author:zty
 * @date: 2019年02月14日 15:46:12
 */
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AddressClient addressClient;
    /**
     * 查询收货地址
     *
     * @param token
     * @return
     */
    @GetMapping("/address/list")
    public ResponseEntity<List<AddressDTO>> queryAddress(@CookieValue("LY_TOKEN") String  token){
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        if (loginUser!=null){
            return ResponseEntity.ok(addressClient.queryAddress(loginUser.getId()));
        }
        return  null;
    }
    /**
     * 创建订单
     * @param orderDto
     * @return
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(@RequestBody @Valid OrderDTO orderDto) {
        return  ResponseEntity.status(HttpStatus.CREATED).body(orderService.createOrder(orderDto));
    }

    /**
     * 根据订单id查询订单
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity<Order> qureyOrderById(@PathVariable("id") Long id){
       ;
        return  ResponseEntity.ok().body(orderService.queryOrderById(id));
    }

    /**
     * 根据订单编号,生成支付链接并返回
     *
     * @param orderId
     * @return
     */
    @GetMapping("url/{orderId}")
    public ResponseEntity<String> queryPayUrl(@PathVariable("orderId")Long orderId){
        return  ResponseEntity.ok(orderService.queryPayUrl(orderId));
    }
    /**
     * 查询支付状态
     *
     * @param orderId
     * @return
     */
    @GetMapping("state/{orderId}")
    public ResponseEntity<Integer> queryPayState(@PathVariable("orderId") Long orderId){
        return ResponseEntity.ok(orderService.queryPayState(orderId).getValue());
    }
    /**
     * @author:zty
     * @date: 2019年02月21日 14:33:27
     * @description  定时清除超时订单,返回sku库存数量
     * @method  clearTimeOutOrder
     * @return org.springframework.http.ResponseEntity<java.lang.Void>
     */
    @GetMapping("repeal")
    public ResponseEntity<Void> clearTimeOutOrder(){
        orderService.clearTimeOutOrder();
        return  ResponseEntity.ok().build();
    }

}
